var express = require('express');
var router = express.Router();
var {
  getDecrypt,
  checkSession
} = require("../utils")

var {Mvs} = require("../utils/model")
var monent = require("moment")
monent.locale();


/* GET home page. */
router.get('/', function(req, res, next) {
 res.render('index', { 
    title: '电影评论管理系统',
    username:req.session.username,
    logintime:monent(req.session.logintime).format('llll')
  });
});

router.get('/login',(req,res)=>{
  var username = req.query.username ? getDecrypt(req.query.username) : '' ;
  res.render('login',{username})})

router.get('/register',(req,res)=>{
  res.render('register')
})

router.get("/logout",(req,res)=>{
  req.session.destroy(()=>{
    res.redirect("/")
  })
})

router.get("/changepass",(req,res)=>{
  res.render('changepass',{
    username:req.session.username
  })
})

router.get("/movie",(req,res)=>{
  checkSession(req,res,()=>{
    var sortobj = {_id:1};
    var query = req.query
    var keyword = query.keyword
    console.log(keyword)
    var obj = {}
    if(keyword){
      obj={
        $or:[
          {title:new RegExp(keyword)},
          {year:new RegExp(keyword)},
          {genres:new RegExp(keyword)},
          {'rating.average':new RegExp(keyword)},
          {'directors.name':new RegExp(keyword)},
        ]
      }
    }else{
      sortobj = {...query,...sortobj}
    }
    console.log(obj)
  
    Mvs.find(obj).sort(sortobj)
    .then(result=>{
      res.render('movie',{
        result,
        username:req.session.username
      })
    })
  })
})



module.exports = router;
